import cv2
import queue
import threading
import numpy as np
# 输入你的摄像头 RTSP 或 HTTP 地址
url = "http://10.193.190.99:4747/video"


class VideoCapture:

    def __init__(self, name):
        self.cap = cv2.VideoCapture(name)
        self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 380)

        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 380)
        self.cap.set(cv2.CAP_PROP_FPS, 30)

        ret = self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
        print("摄像头是否支持0缓冲: ", ret)

        self.isRUN = True



        self.q = queue.Queue()
        self.thread = threading.Thread(target=self._reader, daemon=True)
        self.thread.start()

    # 帧可用时立即读取帧，只保留最新的帧
    def _reader(self):
        while self.isRUN:
            ret, frame = self.cap.read()
            if not ret:
                break
            if not self.q.empty():
                try:
                    self.q.get_nowait()   # 删除上一个（未处理的）帧
                except queue.Empty:
                    pass
            self.q.put(frame)

    def read(self):
        return self.q.get()

    def release(self):
        self.isRUN = False
        self.thread.join()  # 等待线程退出
        self.cap.release()
        cv2.destroyAllWindows()
